<!-- 事件日志 -->
<template>
  <div class="dashboard-editor-container">
    <div style="display:flex;justify-content:space-between;">
      <partitionTree :nodeData="nodeData" :expandArray="expandArray" :addTemplate="false" :defaultExpandAll="false" dialogName="Hardware"
        @handleNodeClick="handleNodeClick" ref="partitionTree" @toggleVisibility="toggleVisibility">
      </partitionTree>
      <div :style="{ width: containerWidth }" class="box"
        style="background:#fff;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
        <el-row style="background: #fff; padding: 16px 16px 0;">
          <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset">
            <el-button type="primary" size="small" @click="lowConfigurationDefinition">低配定义</el-button>
          </connsearch>
          <div class="tabclick">
            <div class="tabitem" @click="handleClick()">
              <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
            </div>
          </div>
          <el-row>
            <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" @tab-click="tabClick">
              <el-tab-pane label="按资产健康统计分析" lazy>
                <el-col :xs="24" :sm="24" :lg="24">
                  <piechart :chartData="pie3Data" @pieclick="echartsClick" title="按资产健康统计分析" />
                </el-col>
              </el-tab-pane>
            </el-tabs>
          </el-row>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }"
            style="padding-right: 8px;margin:16px 0;">
            <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
              <el-table-column label="序号" width="60" type="index"
                :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
              <el-table-column label="部门" show-overflow-tooltip prop="Department" width="120px"></el-table-column>
              <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" width="160px"></el-table-column>
              <el-table-column label="使用者" show-overflow-tooltip prop="UserName" width="120px"></el-table-column>
              <el-table-column label="上报时间" show-overflow-tooltip prop="TransTime" width="180"></el-table-column>
              <el-table-column label="资产总结" show-overflow-tooltip prop="Status" width="100">
                <template slot-scope="{row}">
                  <span style="color:#67C23A" v-show="row.Status === 1">标准资产</span>
                  <span style="color:#E6A23C" v-show="row.Status === 2">低配资产</span>
                  <span style="color:#F56C6C" v-show="row.Status === 3">高龄资产</span>
                  <span style="color:#909399" v-show="row.Status === 4">高龄低配</span>
                </template>
              </el-table-column>
              <el-table-column label="使用时长" show-overflow-tooltip prop="StartDate"></el-table-column>
              <!-- <el-table-column label="主板" show-overflow-tooltip prop="Mainboard" ></el-table-column> -->
              <!-- <el-table-column label="cpu" show-overflow-tooltip prop="Cpu" ></el-table-column> -->
              <el-table-column label="核数" show-overflow-tooltip prop="CpuCoreCount"></el-table-column>
              <el-table-column label="主频" show-overflow-tooltip prop="CpuHZ">
                <template slot-scope="{row}">
                  <span>{{ row.CpuHZ }} GHz</span>
                </template>
              </el-table-column>
              <el-table-column label="内存" show-overflow-tooltip prop="MemSize"></el-table-column>
              <el-table-column label="系统磁盘" show-overflow-tooltip prop="SysDiskSize"></el-table-column>
              <el-table-column label="数据磁盘" show-overflow-tooltip prop="ExtDiskSize"></el-table-column>
              <el-table-column label="操作" width="80px" fixed="right">
                <template slot-scope="scope">
                  <el-button size="mini" type="success" @click="detailsChange(scope.row)">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
              :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
            </el-pagination>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false title="低配定义" :visible.sync="logDialog"
      v-el-drag-dialog width="800px">
      <el-form label-width="170px" :model="resourceForm" :rules="rules" ref="resourceForm">
        <el-form-item label='内存小于等于:' prop="Mem">
          <el-input v-model.number="resourceForm.Mem" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入内存"
            maxlength="10"><template slot="append">G</template></el-input>
        </el-form-item>
        <el-form-item label='磁盘总空间小于等于:' prop="Disk">
          <el-input v-model.number="resourceForm.Disk" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入磁盘总空间"
            maxlength="10"><template slot="append">G</template></el-input>
        </el-form-item>
        <el-form-item label='cpu核数小于等于:' prop="CpuCoreCount">
          <el-input v-model.number="resourceForm.CpuCoreCount" oninput="value=value.replace(/[^\d]/g,'')"
            placeholder="请输入cpu核数" maxlength="10"><template slot="append">个</template></el-input>
        </el-form-item>
        <el-form-item label='cpu主频小于等于:' prop="CpuHZ">
          <el-input v-model.number="resourceForm.CpuHZ" oninput="value=value.replace(/[^\d.]/g,'')" placeholder="请输入cpu主频"
            maxlength="10"><template slot="append">GHz</template></el-input>
        </el-form-item>
        <el-form-item label='高龄资产定义:' prop="Age">
          <el-input v-model.number="resourceForm.Age" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入超过多少年"
            maxlength="10"><template slot="append">年</template></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="logDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog v-el-drag-dialog title="资产详情" :close-on-click-modal="false" :visible.sync="dialogTableVisible" width="70%"
      top="3vh">
      <HardDetail :DeviceObj=DeviceObj></HardDetail>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogTableVisible = false;">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import HardDetail from "@/components/HardDetail"
import piechart from "./components/piechart.vue";
import { parseTime, formatTime3, formatBytes2, GetDeviceTree2 } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { connrequest } from "@/api/firstPage.js"
import partitionTree from "@/components/partitionTree";
export default {
  directives: { elDragDialog },
  components: { connsearch, barchart, piechart, HardDetail, partitionTree },
  data() {
    let that = this
    const checkNumber = (rule, value, callback) => {
      if (!Number.isFinite(value)) {
        callback(new Error('请输入有效数字'));
      } else {
        callback();
      }
    };
    return {
      activeName: "",
      tabTitle: '按资产健康统计分析',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      logDialog: false,
      dialogTableVisible: false,
      tab: false,
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      tableData: [],
      nodeData: [],
      expandArray: [],
      containerWidth: 'calc(100% - 275px)',
      searchform: {},
      options: {},
      nodeobj: {},
      searchobj: {},
      echartsobj: {},
      resourceForm: {},
      DeviceObj: {},
      formOptions: [
        {
          col: 8,
          hidden: false,
          label: "资产类型", // label文字
          prop: "Status", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 0, // 字段初始值,
          placeholder: "请选择严重性等级", // elementui组件属性
          options: [
            { label: '全部', value: 0 },
            { label: '标准资产', value: 1 },
            { label: '低配资产', value: 2 }
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Status = val
            },
          },
        },
        {
          col: 8,
          hidden: false,
          label: "高龄资产", // label文字
          prop: "Age", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: 0, // 字段初始值,
          placeholder: "请选择高龄资产", // elementui组件属性
          options: [
            { label: '全部', value: 0 },
            { label: '标准资产', value: 1 },
            { label: '高龄资产', value: 2 }
          ],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.Age = val
            },
          },
        },
        // {
        //   col: 8,
        //   label: "主板关键字",
        //   prop: "KeyMainboard",
        //   element: "el-input",
        //   placeholder: "请输入主板关键字",
        //   maxlength: 50,
        //   events: {
        //     input(val) {
        //       that.searchform.KeyMainboard = val
        //     },
        //   },
        // },
        // {
        //   col: 8,
        //   label: "cpu关键字",
        //   prop: "KeyCpu",
        //   element: "el-input",
        //   placeholder: "请输入cpu关键字",
        //   maxlength: 50,
        //   events: {
        //     input(val) {
        //       that.searchform.KeyCpu = val
        //     },
        //   },
        // },
        // {
        //   col: 8,
        //   label: "内存关键字",
        //   prop: "KeyMem",
        //   element: "el-input",
        //   placeholder: "请输入内存关键字",
        //   maxlength: 50,
        //   events: {
        //     input(val) {
        //       that.searchform.KeyMem = val
        //     },
        //   },
        // },
        // {
        //   col: 8,
        //   label: "磁盘关键字",
        //   prop: "KeyDisk",
        //   element: "el-input",
        //   placeholder: "请输入磁盘关键字",
        //   maxlength: 50,
        //   events: {
        //     input(val) {
        //       that.searchform.KeyDisk = val
        //     },
        //   },
        // },
      ],
      rules: {
        Mem: [{ validator: checkNumber, trigger: 'blur' }],
        Disk: [{ validator: checkNumber, trigger: 'blur' }],
        CpuCoreCount: [{ validator: checkNumber, trigger: 'blur' }],
        CpuHZ: [{ validator: checkNumber, trigger: 'blur' }],
        Age: [{ validator: checkNumber, trigger: 'blur' }]
      }
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = (Cookies.get('Zhuoguan_DefaultPageLength') || 10) * 1;

    let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
    let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
    let arr = [parseTime(startTime), '']
    this.formOptions.map(item => {
      if (item.label === '日期') {
        item.initValue = arr
      }
    })
    this.$set(this.searchform, 'timeRange', arr)
    this.$set(this.searchform, 'Status', 0)
    this.$set(this.searchform, 'Age', 0)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initData()
  },
  methods: {
    async initData(searchobj = {}) {
      try {
        const { DeviceTree } = await GetDeviceTree2('Hardware', searchobj)
        this.nodeData = DeviceTree
        this.expandArray = [DeviceTree?.[0]?.Name]
      } catch (error) {
        this.$message.error('加载设备树数据失败');
      }
    },
    handleNodeClick(nodeData) {
      this.pageNum = 1
      this.nodeobj = { DepartmentID: nodeData.data.isDevice ? nodeData.data.DepartmentID : nodeData.data.ID, DeviceUUID: nodeData.data.isDevice ? nodeData.data.DeviceUUID : '' }
      this.echartsobj = {}
      this.getData({ ...this.searchobj, ...this.nodeobj })
    },
    toggleVisibility(isHidden) {
      if (isHidden)
        this.containerWidth = '100%';
      else
        this.containerWidth = 'calc(100% - 275px)';
    },
    async lowConfigurationDefinition() {
      const res = await connrequest('GetPCLowerStandard')
      this.resourceForm = { ...res.Data, Disk: res.Data?.Disk / 1000 || 0, Mem: res.Data?.Mem / 1000 || 0, CpuHZ: res.Data?.CpuHZ / 1000 || 0 }
      this.logDialog = true
    },
    async submit() {
      this.$refs.resourceForm.validate(async (valid) => {
        if (valid) {
          const data = {
            Data: {
              ...this.resourceForm,
              Disk: this.resourceForm.Disk * 1000,
              Mem: this.resourceForm.Mem * 1000,
              CpuHZ: this.resourceForm.CpuHZ * 1000,
            }
          }
          const res = await connrequest('SetPCLowerStandard', data)
          if (res.Status.StatusCode === 0) {
            this.logDialog = false
            this.getData()
          }
        }
      });
    },
    detailsChange(row) {
      this.dialogTableVisible = true
      this.DeviceObj = {
        ...row,
        control: true,
      }
    },
    handleChange() { },
    // 获取所有数据
    getData(searchobj = {}) {
      this.GetEventLog(searchobj)
      switch (this.tabTitle) {
        case '按资产健康统计分析':
          this.GetDeviceHardwareSumGroupByHealth(searchobj)
          break;
        default:
          // this.GetDeviceHardwareSumGroupByHealth()
          break;
      }
    },
    echartsClick(val, title) {
      this.pageNum = 1
      if (title === '按资产健康统计分析') {
        let asset = {}
        if (val === '标准资产') {
          asset = { Status: 1, Age: 1 }
        } else if (val === '低配资产') {
          asset = { Status: 2, Age: 1 }
        } else if (val === '高龄资产') {
          asset = { Status: 1, Age: 2 }
        } else if (val === '高龄低配') {
          asset = { Status: 2, Age: 2 }
        }
        this.echartsobj = { ...asset }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      }
    },
    tabClick(row) {
      this.tabTitle = row.label
      switch (row.label) {
        case '按资产健康统计分析':
          this.GetDeviceHardwareSumGroupByHealth({ ...this.searchobj, ...this.nodeobj })
          break;
        default:
          // this.GetDeviceHardwareSumGroupByHealth()
          break;
      }
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          DeviceUUID: this.searchform.DeviceUUID,
          KeyMainboard: this.searchform.KeyMainboard,
          KeyMem: this.searchform.KeyMem,
          KeyCpu: this.searchform.KeyCpu,
          KeyDisk: this.searchform.KeyDisk,
          Status: this.searchform.Status,
          Age: this.searchform.Age,
          ...searchobj
        }
      }
      const res = await connrequest('GetDeviceHardware', data)
      res.Data = res.Data || []
      res.Data = res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        item.StartDate = item.StartDate ? formatTime3(item.StartDate) : '未知'
        item.MemSize = formatBytes2(item.MemSize * 1000000)
        item.SysDiskSize = formatBytes2(item.SysDiskSize * 1000000)
        item.ExtDiskSize = formatBytes2(item.ExtDiskSize * 1000000)
        item.CpuHZ = (item.CpuHZ / 1000).toFixed(2)
        return item
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount || 0
    },
    // 按资产健康统计分析
    async GetDeviceHardwareSumGroupByHealth(searchobj = {}) {
      const data = {
        Filter: {
          DeviceUUID: this.searchform.DeviceUUID,
          KeyMainboard: this.searchform.KeyMainboard,
          KeyMem: this.searchform.KeyMem,
          KeyCpu: this.searchform.KeyCpu,
          KeyDisk: this.searchform.KeyDisk,
          Status: this.searchform.Status,
          Age: this.searchform.Age,
          Descp: this.searchform.Descp || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetDeviceHardwareSumGroupByHealth', data);
      const Device = res.Data?.Device || {};
      const arr = [
        { name: '标准资产', value: Device.HealthDeviceCount || 0 },
        { name: '低配资产', value: Device.LowerDeviceCount || 0 },
        { name: '高龄低配', value: Device.LowerOldDeviceCount || 0 },
        { name: '高龄资产', value: Device.OldDeviceCount || 0 },
      ].filter(item => item.value > 0);
      this.pie3Data = arr
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = { ...val }
      this.searchform = { ...val }
      this.getData({ ...this.echartsobj, ...this.searchobj, ...this.nodeobj })
      this.initData({...this.searchobj})
    },
    // 重置
    reset() {
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map(item => {
        if (item.label === "日期") {
          item.initValue = arr
        } else if (item.label === "资产类型") {
          item.initValue = 0
        } else {
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.echartsobj = {}
      this.searchobj = {}
      this.nodeobj = {}
      this.$set(this.searchform, 'timeRange', arr)
      this.$set(this.searchform, 'Status', 0)
      this.$set(this.searchform, 'Age', 0)
      this.$refs.connsearch.addInitValue()
      this.getData()
      this.initData()
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>